logger = require('../../helpers/logger') __filename

module.exports = (err, req, res, next) ->
  # 打印错误栈
  logger.error err.stack

  # 错误对象类型为object，且msg未指定
  if 'object' is typeof(err) and not err.msg
    err.msg = JSON.stringify err
    err.msg.status = 'failed'

  # 客户端请求头要求返回JSON文档，且错误对象类型为object
  if (req.accepts 'application/json') and (typeof(err) is 'object')
    if 'string' is typeof err?.msg
      try
        err.msg = JSON.parse err?.msg
        err.msg.error = '无法解析的JSON字符串！'
      catch e
        err.msg = e or '未知的解析JSON字符串错误！'
      err.msg.status = 'failed'
    res.status(err.code or 500).json(err.msg)
  # 其余情况直接返回500状态
  else
    res.status(err.code or 500).json({error : err, status: 'failed'})